package com.czk.netty.netty.groupchat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/18 20:47
 */
public class GroupChatClient {
    /**
     * 监听的主机地址
     */
    private final String HOST;
    /**
     * 端口
     */
    private final int PORT;

    /**
     * 初始化
     *
     * @param HOST
     * @param PORT
     */
    public GroupChatClient(String HOST, int PORT) {
        this.HOST = HOST;
        this.PORT = PORT;
    }

    public void run() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 加入相关的handler解码编码器 入站
                        pipeline.addLast("decoder", new StringDecoder());
                        // 出站
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast(new GroupChatClientHandler());
                    }
                });
        try {
            ChannelFuture sync = bootstrap.connect(HOST, PORT).sync();
            // 得到channel
            Channel channel = sync.channel();
            System.out.println("======" + channel.localAddress() + "============");
            // 客户端需要输入信息
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String message = scanner.nextLine();
                channel.writeAndFlush(message + "\n");
            }
        } catch (Exception ex) {

        }

    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 7001).run();
    }
}
